package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.vo.OrderReportVO;
import com.sky.vo.SalesTop10ReportVO;
import com.sky.vo.TurnoverReportVO;
import com.sky.vo.UserReportVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    /**
     * 获取指定时间区间的营业额统计报表
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO getTurnoverStatistics(LocalDate begin, LocalDate end) {
        //存放begin-end的日期集合
        List<LocalDate> date = new ArrayList<>();
        date.add(begin);
        while (!begin.equals(end)) {
            //获取begin的下一天
            begin = begin.plusDays(1);
            date.add(begin);
        }
        //将列表转为字符串，用“,”作为分隔符
        String dateList = StringUtils.join(date, ",");

        //根据日期查询订单表，返回营业额
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate localDate : date) {
            // 查询该日期所有订单中状态为“已完成”的订单，然后统计营业额
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Double turnover = orderMapper.sumAmountByStatusAndLocalTime(beginTime, endTime, Orders.COMPLETED);
            turnover = turnover ==null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        //将营业额列表转化为字符串
        String turnover = StringUtils.join(turnoverList, ",");

        //返回结果
        return TurnoverReportVO.builder()
                .dateList(dateList)
                .turnoverList(turnover)
                .build();
    }

    /**
     * 获取指定时间区间的用户统计报表
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO getUserStatistics(LocalDate begin, LocalDate end) {
        //存放begin-end的日期集合
        List<LocalDate> date = new ArrayList<>();
        date.add(begin);
        while (!begin.equals(end)) {
            //获取begin的下一天
            begin = begin.plusDays(1);
            date.add(begin);
        }
        //将列表转为字符串，用“,”作为分隔符
        String dateList = StringUtils.join(date, ",");

        //存放每天的新增用户数量
        List<Integer> newUser= new ArrayList<>();

        //存放每天的总用户数量
        List<Integer> totalUser= new ArrayList<>();

        for (LocalDate localDate : date) {
            // 查询该日期所有订单中状态为“已完成”的订单，然后统计营业额
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("endTime", endTime);

            //查找截止当前日期总用户数量
            Integer users = userMapper.countByMap(map);
            log.info("当前map;{},当前日期:{},总用户数量：{}",map,localDate, users);
            users = users ==null ? 0 : users;
            totalUser.add(users);

            map.put("beginTime", beginTime);
            //查找当前日期的新增用户数量
            Integer newUsers = userMapper.countByMap(map);
            log.info("当前map:{},当前日期:{},的新增用户数量：{}",map,localDate,newUsers);
            newUsers = newUsers ==null ? 0 : newUsers;
            newUser.add(newUsers);
        }
        //将总用户列表转化为字符串
        String totalUserList = StringUtils.join(totalUser, ",");
        log.info("总用户列表：{}", totalUserList);
        //将新增用户列表转化为字符串
        String newUserList = StringUtils.join(newUser, ",");
        log.info("新增用户列表：{}", newUserList);
        return UserReportVO.builder()
                .dateList(dateList)
                .totalUserList(totalUserList)
                .newUserList(newUserList)
                .build();
    }

    /**
     * 获取指定时间区间的订单统计报表
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO getOrderStatistics(LocalDate begin, LocalDate end) {
        //存放begin-end的日期集合
        List<LocalDate> date = new ArrayList<>();
        date.add(begin);
        while (!begin.equals(end)) {
            //获取begin的下一天
            begin = begin.plusDays(1);
            date.add(begin);
        }

        // 创建每日总订单数列表
        List<Integer> orderCountList = new ArrayList<>();

        // 创建每日有效订单列表
        List<Integer> validOrderCountList = new ArrayList<>();

        //遍历date集合，查询每天的有效订单和总订单
        for (LocalDate localDate : date) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();

            //查询每天的订单总数 select count(id) from orders where  order_time >= '2023-01-01' and order_time <= '2023-01-01'
            map.put("endTime", endTime);
            map.put("beginTime", beginTime);
            Integer totalOrderCount = orderMapper.countByMap(map);
            orderCountList.add(totalOrderCount);

            //查询每天的有效订单数 select count(id) from orders where order_time >= '2023-01-01' and order_time <= '2023-01-01' and status = '已完成'
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.countByMap(map);
            validOrderCountList.add(validOrderCount);
        }
        //每日总订单数列表中的所有数值求和
        Integer totalOrderCount = orderCountList.stream().mapToInt(Integer::intValue).sum();
        //每日有效订单数列表中的所有数值求和
        Integer validOrderCount = validOrderCountList.stream().mapToInt(Integer::intValue).sum();
        //计算订单完成率orderCompletionRate
        double orderCompletionRate = 0.0;
        if (totalOrderCount != 0){
            orderCompletionRate = (double) validOrderCount / totalOrderCount;
        }

        return OrderReportVO.builder()
                .dateList(StringUtils.join(date, ","))
                .orderCompletionRate(orderCompletionRate)
                .orderCountList(StringUtils.join(orderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .build();
    }

    /**
     * 菜品Top10统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> salesTop10 = orderMapper.getSalesTop10(beginTime, endTime);

        //创建两个集合列表，存储菜品名和菜品数量
        List<String> goodsNameList = new ArrayList<>();
        List<Integer> salesCountList = new ArrayList<>();
        //遍历salesTop10
        for (GoodsSalesDTO goodsSalesDTO : salesTop10) {
            goodsNameList.add(goodsSalesDTO.getName());
            salesCountList.add(goodsSalesDTO.getNumber());
        }


        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(goodsNameList, ","))
                .numberList(StringUtils.join(salesCountList, ","))
                .build();
    }
}
